package com.huaxin.common.utils;

import android.text.TextUtils;

import com.huaxin.common.Entity.PlanContentDTO;

import java.util.ArrayList;
import java.util.List;

public class SearchByKey {

    public static List<PlanContentDTO.PlanCotent> filterData(String keyword, List<PlanContentDTO.PlanCotent> SourceDateList){
        List<PlanContentDTO.PlanCotent> filterDateList = new ArrayList<PlanContentDTO.PlanCotent>();

        if(TextUtils.isEmpty(keyword)){
            for (PlanContentDTO.PlanCotent planCotent : SourceDateList) {
                if (planCotent.getPlanTitle_html()!=null) {
                    planCotent.setPlanTitle_html(null);
                }
            }
            filterDateList = SourceDateList;
        }else{
            filterDateList.clear();
            for(PlanContentDTO.PlanCotent sortModel : SourceDateList){
                String name = sortModel.getPlanTitle();
                match(filterDateList, sortModel, keyword);
            }
        }
        // paixu
//        Collections.sort(filterDateList, pinyinComparator);
          return filterDateList;
    }

    private static void match(List<PlanContentDTO.PlanCotent> filterDateList, PlanContentDTO.PlanCotent sortModel, String filterStr) {
        boolean isMatch = false;
        String car_title = sortModel.getPlanTitle();
        int sellingCount = matchText(sortModel,filterStr);
        if (sellingCount!=0) {
            isMatch = true;
            sortModel.setPlanTitle_html("<font color='#f08519'><b>" + car_title.substring(0,sellingCount) + "</b></font>" + car_title.substring(sellingCount));
        }

        int index = car_title.toLowerCase().indexOf(filterStr.toLowerCase().toString());
        int length = filterStr.length();
        if (index != -1) {
            isMatch = true;
            sortModel.setPlanTitle_html(car_title.substring(0,index) + "<font color='#f08519'><b>" + filterStr + "</b></font>" + car_title.substring(index+length));
        }

        if (isMatch) {
            filterDateList.add(sortModel);
        }
    }

    private static int matchText(PlanContentDTO.PlanCotent sortModel, String filterStr ) {
        CharacterParser characterParser = CharacterParser.getInstance();
        int sellingcount = 0;
        String name = sortModel.getPlanTitle();
        String[] sellingArray = characterParser.getSellingArray(name);
        for (String selling : sellingArray) {
            if ("".equals(filterStr)) {
                return sellingcount;
            }
            if (filterStr.startsWith(selling)) {
                sellingcount++;
                filterStr = filterStr.substring(selling.length(),filterStr.length());
            }else if(selling.startsWith(filterStr)){
                sellingcount++;
                return sellingcount;
            }else {
                return 0;
            }
        }
        return sellingcount;
    }

}